package com.learn.xiaoha.sqlsession.result.handle;

import com.google.common.collect.Collections2;
import org.apache.commons.lang3.ArrayUtils;

import java.lang.reflect.Field;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

/**
 * ListResultHandle
 *
 * @author: cyx_jay
 * @date: 2021/2/3 8:52
 */
public  class ListResultHandle<T> implements ResultHandle<List<T>> {


    @Override
    public List<T> handle(ResultSet resultSet, Class t) throws Exception {
        Field[] declaredFields = t.getDeclaredFields();
        List<Object> result = null;
        if (ArrayUtils.isNotEmpty(declaredFields)){
            while (resultSet.next()){
                if (result == null){
                    result = new ArrayList<>(10);
                }
                Object obj = t.newInstance();
                for (Field declaredField : declaredFields) {
                    declaredField.setAccessible(true);
                    declaredField.set(obj,resultSet.getObject(declaredField.getName()));
                }
                result.add(obj);
            }
        }
        return (List<T>) result;

    }


}
